package com.wjk.kylin.id.server.interceptor;

import com.wjk.kylin.id.server.constant.Constants;
import com.wjk.kylin.id.server.util.IpUtil;
import com.wjk.kylin.id.server.util.SysSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Slf4j
@Component
public class BaseInterceptor implements HandlerInterceptor {
    private static final ThreadLocal<Long> THREAD_LOCAL = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //traceId,如果head中有key traceId
//        Optional.ofNullable(request.getHeader(Constants.TRACE_ID_KEY))
//                //如果不为空
//                .ifPresent(traceId -> {
//                    if (StringUtils.isBlank(traceId)) {
//                        traceId = UUID.randomUUID().toString().replace("-", "");
//                        log.info("header traceId is null create new traceId:{}", traceId);
//                    }
//                    MDC.put(Constants.TRACE_ID_KEY, traceId);
//                    SysSession.setTraceId(traceId);
//                });

        //和上面的不一样。head中有没有 key traceId，都会进行下面的处理
        String traceId = request.getHeader(Constants.TRACE_ID_KEY);
        if (StringUtils.isBlank(traceId)) {
            traceId = UUID.randomUUID().toString().replace("-", "");
        }
        MDC.put(Constants.TRACE_ID_KEY, traceId);
        SysSession.setTraceId(traceId);

        //请求开始计时，单位毫秒
        THREAD_LOCAL.set(System.currentTimeMillis());
        //请求信息
        String remoteIp = IpUtil.getRemoteIP(request);
        String uri = request.getRequestURI();

        log.info("请求 ====> 接口：{}, ip：{}", uri, remoteIp);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (StringUtils.isNotBlank(SysSession.getTraceId())) {
            response.setHeader(Constants.TRACE_ID_KEY, SysSession.getTraceId());
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //应答信息
        String uri = request.getRequestURI();

        //计算耗时,单位毫秒
        Long startTime = THREAD_LOCAL.get();
        long endTime = System.currentTimeMillis();
        long executeTime = endTime - startTime;

        if (executeTime > 10 * 1000) {
            log.warn("接口[{}]响应耗时超过10秒!", uri);
        }

        log.info("响应 ===> 接口：{}, 耗时：{}ms", uri, executeTime);

        //
        SysSession.removeTraceId();
        THREAD_LOCAL.remove();
    }
}
